﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpShare.Collections;

namespace SharpShare.Storage.ApplePhotoLibrary {
    internal static class Util {
        public static StorageFile FileFromImage(this Image image, IStorageContainer parent, IStorageContainer librarySource) {
            IStorageFile asset = FindAsset(librarySource, image.ImagePath).AsFile();
            if (asset == null)
                return null;

            string imageName = GetImageName(image);
            StorageFile file = new StorageFile(
                imageName,
                parent,
                (access, share) => {
                    if (access.HasFlag(StorageFileAccess.Write))
                        throw new StorageItemUnauthorizedException();
                    return asset.Open(access, share);
                }) {
                    Length = asset.Length,
                    DateCreated = image.Date,
                    DateModified = image.ModifiedDate
                };

            return file;
        }
        private static string GetImageName(Image image) {
            int periodIndex = image.ImagePath.LastIndexOf('.');
            if (periodIndex == -1) {
                return image.Key;
            }

            string extension = image.ImagePath.Substring(periodIndex, image.ImagePath.Length - periodIndex).ToLower();

            return (image.Key + extension);
        }

        public static DateTime ReadImageTimestamp(double timestamp) {
            DateTime baseTime = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            DateTime date = (baseTime + TimeSpan.FromSeconds(timestamp));
            return date;
        }

        public static IStorageItem FindAsset(IStorageContainer source, string path) {
            Path<string> storagePath = Path.Parse(path);

            Path<string> upToName = storagePath;

            for (; ; ) {
                upToName = new Path<string>(upToName.Components.SkipWhile(c => !c.Equals(source.Name, StringComparison.OrdinalIgnoreCase)).Skip(1));
                if (upToName.Count == 0) {
                    break;
                }

                IStorageItem item = source.Locate(upToName);

                if (item != null) {
                    return item;
                }
            }

            while (storagePath != Path<string>.Empty) {
                IStorageItem item = source.Locate(storagePath);
                if (item != null) {
                    return item;
                }

                storagePath = new Path<string>(storagePath.Components.Skip(1));
            }

            return null;
        }
    }
}
